package com.yourname.www.listen;

import com.yourname.www.dao.JdbcHelper;
import com.yourname.www.entity.User;
import com.yourname.www.frame.LoginFrame;
import com.yourname.www.frame.MainFrame;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class LoginButtonActionListener implements ActionListener {
    private JTextField usernameText;
    private JPasswordField passwordText;
    private JFrame jf;
    public  LoginButtonActionListener(JTextField usernameText,JPasswordField passwordText,JFrame jf){
        this.usernameText = usernameText;
        this.passwordText = passwordText;
        this.jf = jf;
    }
    @Override
    public void actionPerformed(ActionEvent e) {
        //获取用户名和密码
        String username = usernameText.getText().trim();
        //获取密码
        //String password = passwordText.getText().trim();
        String password = new String(passwordText.getPassword());
        //如果没有输入用户名，弹出提示
        System.out.println("单机事件");
        if("".equals(username)){
            //弹出提示消息
            JOptionPane.showMessageDialog(jf, "用户名不能为空","系统提醒",JOptionPane.WARNING_MESSAGE);
            return ;
        }else if("".equals(password)){
            JOptionPane.showMessageDialog(jf, "密码不能为空","系统提醒",JOptionPane.WARNING_MESSAGE);
            return ;
        }
        //连接数据库 检查用户名是否存在 检查密码是否正确
        //根据用户名查找用户
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);

        JdbcHelper jdbcHelper = new JdbcHelper();
        User byUserName = jdbcHelper.getUserInfoByUserName(user);


        //找不到用户
        if(byUserName == null){
            JOptionPane.showMessageDialog(jf, "用户不存在","系统提醒",JOptionPane.WARNING_MESSAGE);
            return ;
        }
        //判断是否已登录
        if(false && byUserName.getIsLogin() >0){
            JOptionPane.showMessageDialog(jf, "请勿重复登录","系统提醒",JOptionPane.WARNING_MESSAGE);
            return ;
        }
        //
        if(!password.equals(byUserName.getPassword())){
            JOptionPane.showMessageDialog(jf, "密码错误","系统提醒",JOptionPane.WARNING_MESSAGE);
            return ;
        }
        //更新最近登录时间
        if(jdbcHelper.updateWhenLoginSuccess(byUserName)){

            JOptionPane.showMessageDialog(jf, "登录成功","系统提醒",JOptionPane.INFORMATION_MESSAGE);
            //关闭登录窗口
            jf.dispose();
            //打开系统主窗口
            new MainFrame(byUserName);

        }else{
            JOptionPane.showMessageDialog(jf, "登录失败，请联系管理员","系统提醒",JOptionPane.WARNING_MESSAGE);
        }
        return ;


    }
}
